package demo;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//lock锁
public class ThreadSafe {

    private static final int N=100_1000;
    private static int a;
    static Lock lock=new ReentrantLock();//平衡锁

    static class SubThread extends Thread {
        @Override
        public void run() {
            lock.lock();
            try{
                for(int i=0;i<N;i++){
                    a++;
                }

            }finally{
                lock.unlock();
            }
        }
    }
    static class SubThread2 extends Thread{

        @Override
        public void run() {
            lock.lock();
            try{
                for(int i=0;i<N;i++){
                    a--;
                }
            }finally{
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws Exception{
        Thread t1=new SubThread();
        t1.start();
        Thread t2=new SubThread2();
        t2.start();

        t1.join();
        t2.join();
        System.out.println(a);
    }
}
